package com.example.demo1.view



import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.TextView
import com.example.demo1.R
import com.google.android.material.tabs.TabLayout


class MyTabLayout : TabLayout {
    private var titles: List<String>? = null

    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!, attrs, defStyleAttr
    ) {
        init()
    }

    private fun init() {
        titles = ArrayList()
        this.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: Tab) {
                /**
                 * 设置当前选中的Tab为特殊高亮样式。
                 */
                if (tab != null && tab.customView != null) {
                    val tab_text = tab.customView!!.findViewById<TextView>(R.id.tab_text)
                    val paint = tab_text.paint
                    paint.isFakeBoldText = true
                    tab_text.setTextColor(resources.getColor(R.color.color_03a9f4))
                    tab_text.setBackgroundResource(R.drawable.tablayout_item_pressed)
                    val tab_layout_indicator =
                        tab.customView!!.findViewById<ImageView>(R.id.tab_indicator)
//                    tab_layout_indicator.setBackgroundResource(R.drawable.tablayout_item_indicator)
                }
            }

            override fun onTabUnselected(tab: Tab) {
                /**
                 * 重置所有未选中的Tab颜色、字体、背景恢复常态(未选中状态)。
                 */
                if (tab != null && tab.customView != null) {
                    val tab_text = tab.customView!!.findViewById<TextView>(R.id.tab_text)
                    tab_text.setTextColor(Color.GRAY)
                    val paint = tab_text.paint
                    paint.isFakeBoldText = false
                    tab_text.setBackgroundResource(R.drawable.tablayout_item_normal)
                    val tab_indicator = tab.customView!!.findViewById<ImageView>(R.id.tab_indicator)
                    tab_indicator.setBackgroundResource(0)
                }
            }

            override fun onTabReselected(tab: Tab) {}
        })
    }

    fun setTitle(titles: List<String>?) {
        this.titles = titles
        /**
         * 开始添加切换的Tab。
         */
        for (title in this.titles!!) {
            val tab = newTab()
            tab.setCustomView(R.layout.tablayout_item)
            if (tab.customView != null) {
                val tab_text = tab.customView!!.findViewById<TextView>(R.id.tab_text)
                tab_text.text = title
            }
            this.addTab(tab)
        }
    }
}